import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:multi_shop/models/address.dart';
import 'package:multi_shop/models/user.dart';
import 'package:multi_shop/network/api_client.dart';

import '../network/api_routes.dart';
import 'package:get_storage/get_storage.dart';
import 'package:dio/dio.dart';
import 'package:path/path.dart' as p;

class UserApi {
  final _http = HttpClient();
  final storege = GetStorage();

  /// 个人信息
  Future<UserInfo> getUserInfo() async {
    final data = await _http.getJson<UserInfo>(
      ApiRoutes.getUserInfo,
      convert: (data) {
        final userInfo = data["user"];
        return UserInfo.fromJson(userInfo);
      },
    );
    storege.write('userInfo', data);
    return data;
  }

  // 获取默认地址
  Future<Address?> getDefaultAddress() async {
    return await _http.getJson<Address?>(
      ApiRoutes.getDefaultAddress,
      convert: (data) {
        if (data["address"] == null) return null;
        final root = Map<String, dynamic>.from(data as Map);
        final addrJson = (root['address'] is Map)
            ? Map<String, dynamic>.from(root['address'] as Map)
            : root;
        return Address.fromJson(addrJson);
      },
    );
  }

  // 获取地址列表
  Future<List<Address>?> getAddressList() async {
    final data = await _http.getJson<List<Address>?>(
      ApiRoutes.getAddressList,
      convert: (data) {
        final list = data["list"] as List?;
        if (list == null) return <Address>[];
        return list
            .map((e) => Address.fromJson(Map<String, dynamic>.from(e)))
            .toList();
      },
    );
    return data;
  }

  // 添加地址
  Future<void> addAddress(Address address) async {
    await _http.postJson<Map<String, dynamic>>(ApiRoutes.addAddress, {
      "address": address,
    });
  }

  // 更新地址
  Future<void> updateAddress(Address address) async {
    await _http.putJson<void>(ApiRoutes.updateAddress, {"address": address});
  }

  // 删除地址
  Future<void> deleteAddress(int id) async {
    await _http.deleteJson<Map<String, dynamic>>(
      query: {'id': id},
      ApiRoutes.deleteAddress,
    );
  }

  //   更新用户信息
  // 全量更新：把整个 user 发给后端
  Future<void> updateUserInfo(UserInfo user) async {
    await _http.putJson<void>(
      ApiRoutes.updateUserInfo,
      {'user': user.toJson()}, // 若后端不需要包一层user，改成 user.toJson()
    );
  }

  // 更新密码
  Future<void> updatePassword({
    required String oldPwd,
    required String newPwd,
    required int type,
  }) async {
    await _http.putJson<void>(ApiRoutes.updatePassword, {
      'old_pwd': oldPwd,
      'new_pwd': newPwd,
      'type': type,
    });
  }

  // 重置密码
  Future<void> resetPassword({
    required String email,
    required String newPwd,
    required String code,
  }) async {
    await _http.postJson<void>(ApiRoutes.resetPassword, {
      'email': email,
      'new_pwd': newPwd,
      'code': code,
    });
  }

  Future<String> uploadFile(File file) async {
    final form = FormData.fromMap({
      'file': await MultipartFile.fromFile(
        file.path,
        filename: p.basename(file.path),
      ),
    });
    final res = await _http.postJson(ApiRoutes.uploadFile, {'file': form});
    return res.data['url'] as String;
  }

  Future<String> uploadFileBytes(Uint8List bytes, String filename) async {
    final form = FormData.fromMap({
      'file': MultipartFile.fromBytes(bytes, filename: filename),
    });
    final res = await _http.postJson(ApiRoutes.uploadFileBytes, {'file': form});
    return res.data['url'];
  }
}
